#!/bin/zsh

GREEN_START="\e[32m"
GREEN_STOP="\e[0m"
RED_START="\e[31m"
RED_STOP="\e[0m"

PHPLDAPADMIN_LOG_FILE=/var/log/phpldapadmin.log

log () {
	echo $1 | /usr/bin/tee -a ${PHPLDAPADMIN_LOG_FILE}
}

function get_pid () {
	PATTERN=$1
	/bin/ps aux|/bin/grep "${PATTERN}" | /bin/sed '/grep/d'| /usr/bin/awk '{print $1}'
}

install_phpldapadmin () {
	echo -n "installing phpldapadmin: "
	PHPLDAPADMIN_INSTALLED=`/sbin/apk list phpldapadmin 2>/dev/null`
	if [[ -z ${PHPLDAPADMIN_INSTALLED} ]]; then
		/srv/entrypoint.d/php-fpm status || /srv/entrypoint.d/php-fpm install
		/sbin/apk add phpldapadmin php-ldap php-gettext php-xml 2> /dev/null
		log "Installed phpldapadmin"
	fi
	echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	if [ -f /etc/nginx/http.d/default.conf ]; then
		echo -n "remove /etc/nginx/http.d/default.conf: "
		/bin/rm /etc/nginx/http.d/default.conf
		echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	fi
	if [ ! -f /etc/nginx/http.d/phpldapadmin.conf ]; then
		echo -n "create /etc/nginx/http.d/phpldapadmin.conf: "
		/bin/cat << EOF >/etc/nginx/http.d/phpldapadmin.conf 
# vim: ft=nginx
server {
	server_name openldap.domain;
	listen 80 default_server;
	listen [::]:80 default_server;
	# listen 443 ssl;
	# listen [::]:443 ssl;
	root /usr/share/webapps/phpldapadmin/htdocs;
	location / {
		index index.php index.html index.htm;
		charset utf-8;
	}
	# You may need this to prevent return 404 recursion.
	location = /404.html {
		internal;
	}
	# PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI协议默认配置.
	# Fastcgi服务器和程序(PHP,Python)沟通的协议.
	location ~ \.php$ {
		# 设置监听端口
		fastcgi_pass   127.0.0.1:9000;
		# 设置nginx的默认首页文件(上面已经设置过了，可以删除)
		fastcgi_index  index.php;
		# 设置脚本文件请求的路径
		fastcgi_param  SCRIPT_FILENAME  \$document_root\$fastcgi_script_name;
		fastcgi_param  ENV_CAPI_DEBUG true;
		fastcgi_param  APP_ENV development;
		# 引入fastcgi的配置文件
		include        fastcgi_params;
	}
}
EOF
		echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	fi
	if [ -f /srv/podman/openldap/phpldapadmin_config.php ]; then
		# 优先使用外部配置文件
		echo -n "copy /etc/phpldapadmin/config.php: "
		/bin/cp /srv/podman/openldap/phpldapadmin_config.php /etc/phpldapadmin/config.php 
		echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	else
		if [ ! -f /etc/phpldapadmin/config.php ]; then
			echo -n "create /etc/phpldapadmin/config.php: "
			# /bin/cp /etc/phpldapadmin/config.php.example /etc/phpldapadmin/config.php
			# # $servers->setValue('login','bind_pass','123321');
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('login','bind_pass','123321');" /etc/phpldapadmin/config.php
			# # $servers->setValue('login','bind_id','cn=root,dc=openldap,dc=domain');
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('login','bind_id','cn=root,dc=openldap,dc=domain');" /etc/phpldapadmin/config.php
			# # $servers->setValue('login','auth_type','cookie');
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('login','auth_type','cookie');" /etc/phpldapadmin/config.php
			# # $servers->setValue('server','base',array('dc=openldap,dc=domain'));
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('server','base',array('dc=openldap,dc=domain'));" /etc/phpldapadmin/config.php
			# # $servers->setValue('server','tls',false);
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('server','tls',false);" /etc/phpldapadmin/config.php
			# # $servers->setValue('server','port',389);
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('server','port',389);" /etc/phpldapadmin/config.php
			# # $servers->setValue('server','host','openldap.domain');
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('server','host','openldap.domain');" /etc/phpldapadmin/config.php
			# # $servers->setValue('server','name','LDAP Server');
			# /bin/sed -i "/$servers->newServer('ldap_pla');/a \$servers->setValue('server','name','LDAP Server');" /etc/phpldapadmin/config.php
			# /bin/sed -i "s/\$servers->setValue('server','name','LDAP Server')/#\$servers->setValue('server','name','LDAP Server');/g" /etc/phpldapadmin/config.php
			/bin/cat > /etc/phpldapadmin/config.php <<EOF
<?php
$config->custom->commands['script'] = array(
	'add_attr_form' => true,
	'add_oclass_form' => true,
	'add_value_form' => true,
	'collapse' => true,
	'compare' => true,
	'compare_form' => true,
	'copy' => true,
	'copy_form' => true,
	'create' => true,
	'create_confirm' => true,
	'delete' => true,
	'delete_attr' => true,
	'delete_form' => true,
	'draw_tree_node' => true,
	'expand' => true,
	'export' => true,
	'export_form' => true,
	'import' => true,
	'import_form' => true,
	'login' => true,
	'logout' => true,
	'login_form' => true,
	'mass_delete' => true,
	'mass_edit' => true,
	'mass_update' => true,
	'modify_member_form' => true,
	'monitor' => true,
	'purge_cache' => true,
	'query_engine' => true,
	'rename' => true,
	'rename_form' => true,
	'rdelete' => true,
	'refresh' => true,
	'schema' => true,
	'server_info' => true,
	'show_cache' => true,
	'template_engine' => true,
	'update_confirm' => true,
	'update' => true
);
$config->custom->appearance['friendly_attrs'] = array(
	'facsimileTelephoneNumber' => 'Fax',
	'gid'                      => 'Group',
	'mail'                     => 'Email',
	'telephoneNumber'          => 'Telephone',
	'uid'                      => 'User Name',
	'userPassword'             => 'Password'
);
$servers = new Datastore();
$servers->newServer('ldap_pla');
$servers->setValue('server','name','MyLDAPServer');
$servers->setValue('server','host','openldap.domain');
$servers->setValue('server','port',389);
$servers->setValue('server','tls',false);
$servers->setValue('server','base',array('dc=openldap,dc=domain'));
$servers->setValue('login','auth_type','cookie');
$servers->setValue('login','bind_id','cn=root,dc=openldap,dc=domain');
$servers->setValue('login','bind_pass','123321');
$config->custom->session['reCAPTCHA-enable'] = false;
$config->custom->session['reCAPTCHA-key-site'] = '<put-here-key-site>';
$config->custom->session['reCAPTCHA-key-server'] = '<put-here-key-server>';
?>
EOF
			echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
		fi
	fi
	echo -n "fix /usr/share/webapps/phpldapadmin/lib/common.php: "
	/bin/sed -i 's/^error_reporting(E_ALL);$/# error_reporting(E_ALL);/g' /usr/share/webapps/phpldapadmin/lib/common.php
	/bin/sed -i '/# error_reporting(E_ALL);/a error_reporting(E_ALL \& ~ E_DEPRECATED);' /usr/share/webapps/phpldapadmin/lib/common.php
	/bin/sed -i '/# error_reporting(E_ALL);/d' /usr/share/webapps/phpldapadmin/lib/common.php
	echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	# info.php
	/bin/cat > /usr/share/webapps/phpldapadmin/htdocs/info.php <<EOF
<?php
	phpinfo();
?>
EOF
}

status_phpldapadmin () {
	echo -n "check status phpldapadmin: "
	PHPLDAPDMIN_NGINX_CONF=/etc/nginx/http.d/phpldapadmin.conf
	if [ ! -f ${PHPLDAPDMIN_NGINX_CONF} ]; then
		log "[ "${RED_START}"FAILED"${RED_STOP}" ]"
		log "PHPLDAPDMIN_NGINX_CONF file not found: ${PHPLDAPDMIN_NGINX_CONF} "
		return 1
	fi
	PHPLDAPDMIN_PHP_CONF=/etc/phpldapadmin/config.php
	if [ ! -f ${PHPLDAPDMIN_PHP_CONF} ]; then
		log "PHPLDAPDMIN_PHP_CONF file not found: ${PHPLDAPDMIN_PHP_CONF}"
		return 1
	fi
	IS_NGINX_RUNNING=`/bin/ps aux | /bin/grep "nginx: master" | /bin/sed '/grep/d' `
	if [ -z ${IS_NGINX_RUNNING} ]; then
		log "nginx is not running"
		return 1
	fi
	log "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	return 0
}

start_phpldapadmin () {
	echo -n "starting phpldapadmin: "
	install_phpldapadmin
	echo "start php-fpm"
	/srv/entrypoint.d/php-fpm start
	echo "starting phpldapadmin: reload nginx"
	/srv/entrypoint.d/nginx reload
	echo "starting phpldapadmin: [ "${GREEN_START}"OK"${GREEN_STOP}" ]"
}

main ()  {
	action=$1
	case $action in
		status)
			status_phpldapadmin
			;;
		start)
			start_phpldapadmin
			;;
		install)
			install_phpldapadmin
			;;
		*)
	esac
}

main $@
